package com.shopping_back.controller;

import com.shopping_back.common.Result;
import com.shopping_back.pojo.entity.MemberOrder;
import com.shopping_back.service.IUserAccountService;
import com.shopping_back.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shopping_back.pojo.dto.LoginDTO;
import com.shopping_back.pojo.dto.UserRegisterDTO;
import com.shopping_back.pojo.entity.UserAccount;
import com.shopping_back.pojo.entity.UserProfile;
import com.shopping_back.service.CaptchaService;
import com.shopping_back.service.IUserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shopping_back.util.TokenUtil;

/**
 * <p>
 * 用户账户表 前端控制器
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@RestController
@RequestMapping("/api/user-account")
@RequiredArgsConstructor
public class UserAccountController {
    final IUserAccountService userAccountService;
    final IUserProfileService userProfileService;
    final CaptchaService captchaService;
    final TokenUtil tokenUtil;
    final MemberService memberService;

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO dto) {
        // 验证码校验
        boolean captchaOK = captchaService.verifyEmailCaptcha(dto.getEmail(), dto.getEmailCode());
        if (!captchaOK) {
            return Result.error("验证码错误");
        }

        // 用户名查重
        boolean userExist = userAccountService.existsByUsername(dto.getUsername());
        if (userExist) {
            return Result.error("用户名已存在");
        }

        // 邮箱查重
        boolean emailExist = userAccountService.existsByEmail(dto.getEmail());
        if (emailExist) {
            return Result.error("邮箱已注册");
        }

        // 构造 user_account 实体
        UserAccount userAccount = new UserAccount();
        userAccount.setUsername(dto.getUsername());
        userAccount.setEmail(dto.getEmail());
        userAccount.setMobile(dto.getPhone());
        userAccount.setUserType("merchant".equalsIgnoreCase(dto.getIdentity()) ? 1 : 0);
        userAccount.setStatus(true);

        String salt = UUID.randomUUID().toString().replace("-", "");
        userAccount.setSalt(salt);
        userAccount.setPasswordHash(encryptPassword(dto.getPassword(), salt));

        userAccount.setCreateTime(LocalDateTime.now());
        userAccount.setUpdateTime(LocalDateTime.now());

        // 保存到 user_account 表
        boolean accountSaved = userAccountService.save(userAccount);
        if (!accountSaved) {
            return Result.error("注册失败");
        }



        if (userAccount.getUserType() == 0) { // 0表示买家
            // 构造 user_profile 实体
            UserProfile userProfile = new UserProfile();
            userProfile.setUserId(userAccount.getId()); // 使用 user_account 的主键作为外键
            userProfile.setRealName(dto.getRealName());
            userProfile.setIdCard(dto.getIdCard());
            userProfile.setAvatarUrl(dto.getAvatarUrl());
            userProfile.setGender(dto.getGender());
            userProfile.setBirthday(dto.getBirthday());
            userProfile.setCreateTime(LocalDateTime.now());
            userProfile.setUpdateTime(LocalDateTime.now());

            // 保存到 user_profile 表
            boolean profileSaved = userProfileService.save(userProfile);
            MemberOrder order = new MemberOrder();
            order.setUserId(userAccount.getId());
            order.setLevel(1); // 默认银米会员
            order.setStartDate(userAccount.getCreateTime().toLocalDate()); // 注册当天
            order.setEndDate(userAccount.getCreateTime().toLocalDate()); // 无结束日期
            order.setAmount(BigDecimal.ZERO);
            order.setStatus(1); // 有效状态
            memberService.save(order); // 需要注入MemberOrderService
        }

        return Result.success(userAccount);
    }


    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO dto) {
        // 1. 参数校验
        if ((dto.getEmail() == null || dto.getEmail().isEmpty()) &&
                (dto.getPhone() == null || dto.getPhone().isEmpty())) {
            return Result.error("邮箱或手机号不能为空");
        }

        // 2. 根据登录方式查询用户
        UserAccount user = null;
        if (dto.getEmail() != null) {
            // 邮箱登录验证
            if (dto.getVerificationCode() == null || dto.getVerificationCode().isEmpty()) {
                return Result.error("验证码不能为空");
            }

            boolean ok = captchaService.verifyEmailCaptcha(dto.getEmail(), dto.getVerificationCode());
            if (!ok) return Result.error("验证码错误");

            user = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
                    .eq(UserAccount::getEmail, dto.getEmail()));
        } else {
            // 手机号登录验证
            if (dto.getPassword() == null || dto.getPassword().isEmpty()) {
                return Result.error("密码不能为空");
            }

            user = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>()
                    .eq(UserAccount::getMobile, dto.getPhone()));

            // 密码校验（确保user不为null后再校验）
            if (user != null) {
                String encrypted = encryptPassword(dto.getPassword(), user.getSalt());
                if (!encrypted.equals(user.getPasswordHash())) {
                    return Result.error("密码错误");
                }
            }
        }

        if (user == null) {
            return Result.error("用户不存在");
        }

        // 3. 身份校验
        int wantType = "merchant".equalsIgnoreCase(dto.getIdentity()) ? 1 : 0;
        Integer userType = user.getUserType();
        if (userType == null) {
            return Result.error("用户类型未设置，请联系管理员");
        }
        if (!userType.equals(wantType)) {
            return Result.error("身份不符");
        }

        // 4. 生成token
        UserProfile profile = userProfileService.getByUserId(user.getId());

        // 安全获取头像 URL，避免 profile 为空导致空指针
        String avatarUrl = (profile != null && profile.getAvatarUrl() != null)
                ? profile.getAvatarUrl()
                : "http://localhost:8080/assets/default.png";

        String identify = null;
        if (wantType == 1){
            identify = "merchant";
        }else{
            identify = "user";
        }

        LoginDTO userResponse = new LoginDTO();
        JSONObject json = JSONUtil.createObj()
                .put("userId", user.getId())       // 数据库中的用户ID
                .put("username", user.getUsername()) // 数据库中的用户名
                .put("email", user.getEmail())
                .put("identity", identify);
        String token = tokenUtil.createToken(json);
        userResponse.setToken(token);

        Map<String, Object> resultMap = Map.of(
                "userId", user.getId(),
                "username", user.getUsername(),
                "email", user.getEmail(),
                "avatar", avatarUrl,
                "token", token
        );

        return Result.success("登录成功", resultMap);
    }

    // 密码加密方法（示例：使用SHA-256）
    private String encryptPassword(String password, String salt) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
            md.update((password + salt).getBytes());
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (Exception e) {
            System.out.println("密码加密失败：" + e.getMessage());
            throw new RuntimeException("密码加密失败", e);
        }
    }

    @DeleteMapping("/delete")
    public Result deleteAccount(@RequestParam Long id) {
        userAccountService.deleteAccount(id);
        return Result.success("账号注销成功");
    }

    @PutMapping("/reset-password")
    public Result resetPassword(@RequestParam Long id, @RequestParam String password, @RequestParam String repassword) {
        userAccountService.resetPassword(id, password, repassword);
        return Result.success("修改成功");
    }

    /** 管理员获取用户列表（可按状态筛选） */
    @GetMapping("/admin/list")
    public Result list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) Integer status,
                       @RequestParam(required = false) String keyword) {
        return Result.success(userAccountService.listAll(pageNum, pageSize, status, keyword));
    }

    /** 禁用用户：status -> 0 */
    @PostMapping("/admin/{id}/disable")
    public Result disable(@PathVariable Long id) {
        userAccountService.changeStatus(id, false);
        return Result.success();
    }

    /** 启用用户：status -> 1 */
    @PostMapping("/admin/{id}/enable")
    public Result enable(@PathVariable Long id) {
        userAccountService.changeStatus(id, true);
        return Result.success();
    }
}